<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :permission="permissionList"
      :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
      @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
      @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
      <template #menu="{ row, index, size }">
        <!-- <el-button type="text" @click="handleAudit(row, index)">审核</el-button> -->
        <el-button type="text" @click="handleView(row, index)">详情</el-button>
        <el-button v-if="row.status === 1" type="text" style="color: #67C23A;"
          @click="handleOpenedDeactivate(row, 'start', '启用')">启用</el-button>
        <el-button v-if="row.status === 0" type="text" style="color: #F56C6C;"
          @click="handleOpenedDeactivate(row, 'stop', '禁用')">禁用</el-button>
        <!-- <el-button type="text" style="color: #F56C6C;" @click="handleDelete(row)">删除</el-button> -->
      </template>

    </avue-crud>
  </basic-container>
</template>

<script>
import { mapGetters } from "vuex";
import { getList, setStatus, deleteUser } from "./api";

export default {
  data () {
    return {
      form: {},
      query: {},
      loading: false,
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      selectionList: [],
      option: {
        menuType: "button",
        height: "auto",
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: false,
        index: true,
        indexLabel: "序号",
        searchBtnText: "提交",
        searchBtnIcon: "提交",
        emptyBtnText: "重置",
        emptyBtnIcon: "重置",
        viewBtn: false,
        addBtn: false,
        addBtnText: "添加",
        addBtnIcon: "el-icon-plus",
        editBtn: false,
        editBtnText: "",
        selection: false,
        dialogClickModal: false,
        delBtn: false,
        delBtnText: "",
        labelWidth: 110,
        searchLabelWidth: 100,
        dataKey: "id",
        column: [
          {
            label: "关键词",
            prop: "keyword",
            search: true,
            hide: true,
            display: false,
            searchPlaceholder: "请输入电话/昵称",
          },
          {
            label: "是否车主",
            prop: "is_car_owner",
            search: true,
            hide: true,
            display: false,
            type: "select",
            searchPlaceholder: "请选择是否车主",
            dicData: [
              {
                label: "否",
                value: 0,
              },
              {
                label: "是",
                value: 1,
              },
            ],
          },
          {
            label: "车主类型",
            prop: "car_owner_type",
            search: true,
            hide: true,
            display: false,
            type: "select",
            searchPlaceholder: "请选择车主类型",
            dicData: [
              {
                label: "个人车主",
                value: 1,
              },
              {
                label: "营运车主",
                value: 2,
              },
            ],
          },
          {
            label: "状态",
            prop: "status",
            search: true,
            hide: true,
            display: false,
            type: "select",
            searchPlaceholder: "请选择状态",
            dicData: [
              {
                label: "启用",
                value: 0,
              },
              {
                label: "禁用",
                value: 1,
              },
            ],
          },
          {
            label: "用户手机号",
            prop: "phone",
          },
          {
            label: "授权微信昵称",
            prop: "nickname",
          },
          {
            label: "是否车主",
            prop: "is_car_owner_text",
          },
          {
            label: "车主类型",
            prop: "car_owner_type_text",
          },
          {
            label: "诚信值",
            prop: "honesty",
          },
          {
            label: "账号状态",
            prop: "status_text",
          },
          {
            label: "创建时间",
            prop: "created_at",
          },
        ],
      },
      data: [],
      currentItemData: null,
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    permissionList () {
      return {
        addBtn: this.vaildData(this.permission.user_add, true),
        viewBtn: this.vaildData(this.permission.user_view, true),
        delBtn: this.vaildData(this.permission.user_delete, true),
        editBtn: this.vaildData(this.permission.user_edit, true),
      };
    },
    ids () {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  mounted () {
    this.onLoad(this.page);
  },
  methods: {
    // 详情相关
    handleView (data) {
      this.$router.push({
        path: "/userManagement/detail",
        query: {
          id: data.id,
        },
      });
    },
    // 审核相关
    handleAudit (data) {
      this.$router.push({
        path: "/userManagement/auditDetail",
      });
    },

    // 删除用户
    handleDelete (data) {
      this.$confirm("确定删除该用户吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deleteUser(data.id);
        })
        .then(() => {
          this.$message.success("删除成功");
          this.onLoad(this.page, this.query);
        })
        .catch((err) => {
          if (err !== "cancel") {
            console.error("删除失败:", err);
            this.$message.error("删除失败");
          }
        });
    },

    // 启用 / 禁用 相关
    handleOpenedDeactivate (data, status, text) {
      let param = {
        id: data.id,
        status: status === 'start' ? 0 : 1,
      };
      if (text === "启用" && data.honesty == 0) {
        this.$confirm(
          `当前账号诚信值低于0不可启用，请在详情页面管理诚信值`,
          `${text}账户`,
          {
            confirmButtonText: "去管理",
            cancelButtonText: "取消",
            type: "warning",
            icon: "none",
          }
        )
          .then(() => {
            return setStatus(param);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.$refs.crud.toggleSelection();
          });
        return;
      }
      this.$confirm(`确定将选择用户${text}?`, `${text}账户`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return setStatus(param);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen (done, type) {
      done();
    },
    searchReset () {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange (params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange (list) {
      this.selectionList = list;
    },
    selectionClear () {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange (currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange () {
      this.onLoad(this.page, this.query);
    },
    onLoad (page, search = {}) {
      this.loading = true;
      let param = {
        page: page.currentPage,
        size: page.pageSize,
      };

      // 只传递有值的搜索参数
      const searchParams = {};
      if (search.keyword && search.keyword.trim()) {
        searchParams.keyword = search.keyword.trim();
      }
      if (search.is_car_owner !== undefined && search.is_car_owner !== '') {
        searchParams.is_car_owner = search.is_car_owner;
      }
      if (search.car_owner_type !== undefined && search.car_owner_type !== '') {
        searchParams.car_owner_type = search.car_owner_type;
      }
      if (search.status !== undefined && search.status !== '') {
        searchParams.status = search.status;
      }

      getList({ ...param, ...searchParams }).then((res) => {
        if (res.err === 0) {
          const resData = res.data;
          // 使用 pagination 中的分页信息
          this.page.total = resData.pagination.total;
          this.page.currentPage = resData.pagination.page;
          this.page.pageSize = resData.pagination.size;
          // 使用 list 中的数据
          this.data = resData.pagination.list;
        } else {
          this.$message.error(res.msg || '获取数据失败');
        }
        this.loading = false;
        this.selectionClear();
      }).catch((error) => {
        this.$message.error('获取数据失败');
        this.loading = false;
      });
    },
    toggleSelection (rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.blue-normal {
  color: #0e77d1;
  display: inline-block;
  display: flex;
  align-items: center;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    /**控制形状**/
    background-color: #0e77d1;
    /**控制图标颜色**/
    margin-right: 4px;
    /**图标与文字距离**/
  }
}

.green-normal {
  color: #00a854;
  display: inline-block;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    /**控制形状**/
    background-color: #00a854;
    /**控制图标颜色**/
    margin-right: 4px;
    /**图标与文字距离**/
  }
}

.red-normal {
  color: #d9001b;
  display: inline-block;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    /**控制形状**/
    background-color: #d9001b;
    /**控制图标颜色**/
    margin-right: 4px;
    /**图标与文字距离**/
  }
}
</style>
